#!/bin/bash

# Copyright 2020, Mark Callow
# SPDX-License-Identifier: Apache-2.0

# Script to generate version number files using the output of git
# describe.

# A file of this name will be created in the subdir (object) for which a
# version number is being generated.
VF=version.h
DEF_VER=v4.0

LF='
'

function genversion() {
  # Try git-describe, then default.
  if [ -d ${GIT_DIR:-.git} -o -f .git ]; then
    if [ -z "$1" ]; then
      # Get version number for HEAD revision of repo.
      VN=$(git describe --match "v[0-9]*" HEAD 2>/dev/null)
    else
        # Get version number containing the object identified in
        # $1.
        VN=$(git describe --contains --match "v[0-9]*" $(git rev-list -1 HEAD $1) 2>/dev/null)
      if [ -z "$VN" ]; then
        # If no containing tag, get version number for $1 based on
        # previous tag.
        VN=$(git describe --match "v[0-9]*" $(git rev-list -1 HEAD $1) 2>/dev/null)
      fi
    fi
    case "$VN" in
    *$LF*) (exit 1) ;;
    v[0-9]*)
        git update-index -q --refresh
        test -z "$(git diff-index --name-only HEAD --)" ||
        VN="$VN-dirty" ;;
    esac
  else
      VN="$DEF_VER"
  fi
}

# Write the version file, if the new version is different than the
# existing one.
function setfile() {
  local VC
  local verstring=$1_VERSION
  if [ -r $2 ]; then
    VC=$(grep $verstring $2 | sed -e "s/^#define $verstring //")
  else
    VC=unset
  fi
  if [ $force -eq 1 -o "$VN" != "$VC" ]; then
    echo "/*" > $2
    if [ "$1" = "LIBKTX" ]; then
      (echo "// [API version]"
      echo "@par API Version"
      echo "$DEF_VER"
      echo "// [API version]") >> $2
    fi
    (echo "// [Code version]"
    echo "$VN"
    echo "// [Code version]"
    echo "*/"
    echo "#define $verstring $VN"
    echo "#define $1_DEFAULT_VERSION $DEF_VER.__default__") >> $2
  fi
}

# Figure out the object name and write its version file.
function writeversion() {
  genversion $1
  local vfp;
  if [ -z "$1" ]; then
    vfp=$VF
  else
    vfp=$1/$VF
  fi
  if [ "$1" = "lib" ]; then
    ON=LIBKTX
    setfile $ON $1/$VF
  else
    ON=$(basename $1)
    ON=$(echo $ON | tr [:lower:] [:upper:])
    setfile $ON $1/$VF
  fi
}

function usage() {
    echo "Usage: $0 [-a] [-f] [<object>]"
    exit 1
}

force=0
write_all=0;
args=$(getopt afo: $*)

set -- $args
for i; do
  case "$i" in
    -a) write_all=1;
        shift;;
    -f) force=1;
        shift;;
    -o) VF=$2; shift; shift;;
    --) shift; break;;
  esac
done

case $# in
  0) if [ $write_all -ne 1 ]; then usage; fi;;
  1) OBJ=$1;;
  2) usage;;
esac

if [ $write_all -eq 1 ]; then
  for i in lib tools/*; do
    if [ -d $i -a "$i" != "tools/package" ]; then
      writeversion $i
    fi
  done
else
  writeversion $OBJ
fi

# vim:ai:ts=4:sts=4:sw=2:expandtab:textwidth=70
